using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 范围攻击组件，先使用GetEnemiesInSectorRange获取扇形范围内的所有敌人，然后对敌人造成伤害
/// </summary
[Serializable]
public class SectorAttackComponent : AttackComponent
{
    public float attackAngle;
    private List<Entity> CanAttackEntitys = new List<Entity>();

    public void SetAttackEntitys(List<Entity> entities)
    {
        CanAttackEntitys.Clear();
        for (int i = 0; i < entities.Count; i++)
        {
            CanAttackEntitys.Add(entities[i]);
        }
    }
    public override void ApplyDamage()
    {
        List<Entity> enemiesInRange = GetEnemiesInSectorRange();

        foreach (Entity enemy in enemiesInRange)
        {
            if (enemy != null && enemy.gameObject.activeInHierarchy && !enemy.GetEcsComponent<HpComponent>().IsDead)
            {
                enemy.GetEcsComponent<HpComponent>().TakeDamage(attackPower, entity.gameObject);
            }
        }
        isAttacking = false;
    }

    // 获取扇形范围内的所有敌人
    private List<Entity> GetEnemiesInSectorRange()
    {
        List<Entity> enemiesInRange = new List<Entity>();

        Vector3 playerForward = entity.transform.forward;
        Vector3 playerPosition = entity.transform.position;

        foreach (Entity enemy in CanAttackEntitys)
        {
            if (enemy.HasEcsComponent<HpComponent>()) continue; //有HP组件的实体才能被攻击，没有HP组件的实体直接默认他不能被攻击就行了
            if(enemy.GetEcsComponent<HpComponent>().IsDead) continue; // 如果敌人已经死亡，则跳过

            Vector3 directionToEnemy = (enemy.transform.position - playerPosition).normalized;
            float distanceToEnemy = Vector3.Distance(playerPosition, enemy.transform.position);

            // 检查距离
            if (distanceToEnemy <= AttackRange)
            {
                // 检查角度 - 忽略Y轴差异
                directionToEnemy.y = 0;
                Vector3 playerForwardFlat = playerForward;
                playerForwardFlat.y = 0;
                playerForwardFlat.Normalize();

                float angle = Vector3.Angle(playerForwardFlat, directionToEnemy);
                if (angle <= attackAngle / 2f)
                {
                    enemiesInRange.Add(enemy);
                }
            }
        }

        return enemiesInRange;
    }
}
